//
//  MGLoginController.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/9/5.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGLoginController.h"
#import "MGCaptchaController.h"

#import <AuthenticationServices/AuthenticationServices.h>

#import "MGLoginView.h"

@interface MGLoginController () <ASAuthorizationControllerDelegate>
@property (nonatomic, strong) MGLoginView *loginView;

@end

@implementation MGLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.loginView = [MGLoginView createViewAtSuperView:self.view constraintBlock:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset([self customPageHeaderHeight]);
    } configureBlock:nil];
    
    @weakify(self);
    self.loginView.platformSelectBlock = ^(NSInteger index) {
        @strongify(self);
        if (index == 0) {
            [self _handleAppleLogin];
        }
    };
    
    self.loginView.getCaptchaBlock = ^(NSString *text) {
        @strongify(self);
        [self handleGetCaptchaWithPhoneNum:text];
    };
}

- (void)handleGetCaptchaWithPhoneNum:(NSString *)phoneNum {
    self.refreshAlertView = [MGAlertView showQueryAlertView];
    
    @weakify(self);
    [MGReqManager.shared getCaptchaWithPhoneNum:phoneNum successBlock:^(id data, NSDictionary *params) {
        @strongify(self);
        [self.refreshAlertView closeAlertView];
        [YYBAlertView showAlertViewWithStatusString:@"验证码获取成功"];
        [YYBViewRouter openOnClass:[MGCaptchaController class] configureBlock:^(MGCaptchaController *obj) {
            obj.phoneNum = phoneNum;
        }];
    } errorBlock:^(NSError *error, NSDictionary *params) {
        @strongify(self);
        [YYBAlertView showAlertViewWithError:error dismissAlertView:self.refreshAlertView];
    }];
}

//- (void)_handleWechatLogin {
//    SendAuthReq *req = [[SendAuthReq alloc] init];
//    req.scope = @"snsapi_userinfo";
//    // 第三方向微信终端发送一个 SendAuthReq 消息结构
//    [WXApi sendReq:req completion:^(BOOL success) {
//
//    }];
//}

- (void)_handleAppleLogin {
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
        appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
        authorizationController.delegate = self;
        [authorizationController performRequests];
    }
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
//    [YYBAlertView showAlertViewWithStatusString:@"登录出错"];
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
    NSString *authorization_code = [[NSString alloc] initWithData:appleIDCredential.authorizationCode encoding:NSUTF8StringEncoding];
    
    NSString *nickName = @"";
    if (appleIDCredential.fullName.familyName && appleIDCredential.fullName.givenName) {
        nickName = [NSString stringWithFormat:@"%@ %@",appleIDCredential.fullName.familyName, appleIDCredential.fullName.givenName];
    }
    
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    NSString *client_id = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    
    [parameters setObject:client_id forKey:@"client_id"];
    [parameters setObject:authorization_code forKey:@"authorization_code"];
    [parameters setObject:nickName forKey:@"name"];
    [parameters setObject:appleIDCredential.user forKey:@"user"];
    if (appleIDCredential.email) {
        [parameters setObject:appleIDCredential.email forKey:@"email"];
    }
    
    @weakify(self);
    self.refreshAlertView = [MGAlertView showQueryStringAlertViewWithString:@"正在登录" inView:nil isResizeContainer:NO];
    [MGReqManager.shared getAppleLoginResultWithParameters:parameters successBlock:^(id data, NSDictionary *params) {
        @strongify(self);
        [self.refreshAlertView closeAlertView];
        [MGUserModel configUserInfo:data];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } errorBlock:^(NSError *error, NSDictionary *params) {
        @strongify(self);
        [YYBAlertView showAlertViewWithError:error dismissAlertView:self.refreshAlertView];
    }];
}

@end
